package com.zluyuer.ermu.msg;

import java.util.HashMap;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;


public class MessageParser {
    
    private static Map<String, Class<?>> clazzs = new HashMap<String, Class<?>>();

    public static void register(String msgCode, Class<?> clazz) {
        clazzs.put(msgCode, clazz);
    }
    
    public static Message parse(String xml) {
        Document document = null;
        try {
            document = DocumentHelper.parseText(xml);
        } catch (DocumentException e) {
            throw new IllegalArgumentException("Error parse xml");
        }
        
        String msgCode = getMsgCode(document);
        if (msgCode == null || msgCode.equals("")) {
            throw new IllegalArgumentException("Could not find msgCode");
        }
        
        Class<?> clazz = clazzs.get(msgCode);
        if (clazz == null) {
            throw new IllegalArgumentException("Count not find class info for: " + msgCode);
        }
        
        Message msg = null;
        try {
            msg = (Message)clazz.newInstance();
            msg.parse(document);
        } catch (Exception e) {
            throw new IllegalArgumentException("Error parse msg " + msgCode + ": " + e.getMessage());
        }
        
        return msg;
    }
    
    private static String getMsgCode(Document doc) {
        return doc.getRootElement().element("head").elementText("code");
    }
}
